<template>
  <el-row class="form-deal-firealarm" type="flex" justify="center" v-loading="loading">
    <el-col>
      <el-form label-width="130px" :model="handleForm" :rules="handleFormRules" ref="handleForm" @submit.native.prevent>
        <div v-if="dataObj.length==1" class="row-img">
          <el-image
            v-if="picUrl"
            :src="picUrl"
            fit="contain"
            @click="onPreview(dataObj,1)"
            style="width: 192px; height: 108px;"
          ></el-image>
          <div class="desc">{{dataObj.selfDesc}}</div>
        </div>
        <el-form-item label="处理类型：" prop="handleType">
          <el-select filterable @change="handleSelectChange" v-model="handleForm.handleType" placeholder="请选择处理类型">
            <el-option
              v-for="item in handleTypeOptions"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="添加备注：" prop="remark">
          <el-input v-model="handleForm.remark" type="textarea" placeholder="请输入火灾描述" clearable></el-input>
        </el-form-item>
        <el-form-item label="现场图片：">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="true"
            ref="upload"
            list-type="picture-card"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemovePic"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :on-preview="$imgPreview"
            :file-list="fileList"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="现场视频：">
          <el-upload
            :action="QINIUUPLOADURL"
            :data="qiniuData"
            :limit="3"
            :on-success="onVideoUploadSuccess"
            :on-remove="onRemoveVideo"
            :on-error="handleError"
            :before-upload="beforeUploadVideo"
            :file-list="videoList"
            accept="video/mp4, video/mpeg"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click="closeFun">取消</el-button>
          <el-button type="primary" @click="submitHandle('handleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <image-viewer ref="ImageViewer" :origin-list="originList"></image-viewer>
  </el-row>
</template>
<script>
import util from '@/utils/util'
import { qnToken } from '@/api/api'
import { getDictByCode } from '@/api/dic'
import { alarmHandle } from '@/api/spray'
import ImageViewer from '@/components/TransAiPic/ImageViewer'
import { mapState } from 'vuex'

export default {
  name: 'DealWithPolice',
  components: { ImageViewer },
  props: {
    dataObj: {
      required: true,
    },
    closeFun: {
      required: true,
    },
    formatPicUrl: {
      type: Function,
      default: function () {},
    },
    relatedAlarms: {
      type: Array,
      default: function () {
        return []
      },
    },
  },
  data() {
    return {
      defaultImg: this.GLOBAL.defaultImg,
      loading: false,
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
      },
      fileList: [],
      videoList: [],
      handleTypeOptions: [], // 处理类型下拉框选项
      handleForm: {
        operator: '',
        alarmId: '',
        handleAlarmIds: '',
        deviceIds: '',
        handleType: '',
        handleTypeName: '',
        remark: '',
        picUrls: '',
        audioUrls: '',
      },
      handleFormRules: {
        handleType: [
          { required: true, message: '请选择处理类型', trigger: 'change' },
        ],
      },
      originList: [],
      picUrl: '',
    }
  },
  computed: {
    ...mapState(['userinfo']),
  },
  watch: {},
  created() {
    this.handleForm.operator = this.userinfo.accountName
    this.handleForm.alarmId = this.dataObj.id
    this.handleForm.handleAlarmIds =
      this.dataObj.alarmType == 2
        ? this.dataObj.id
        : this.relatedAlarms
            .map((n) => {
              return n.id
            })
            .join(',')
    this.handleForm.deviceIds =
      this.dataObj.alarmType == 2
        ? this.dataObj.deviceId
        : this.relatedAlarms
            .map((n) => {
              return n.deviceId
            })
            .join(',')
    if (this.dataObj.picturesUrls) {
      this.picUrl = this.formatPicUrl(this.dataObj.picturesUrls)
    } else {
      this.picUrl = this.dataObj.detailPic
        ? JSON.parse(this.dataObj.detailPic).icon || this.defaultImg
        : this.defaultImg
    }
    this.getToken() // 获取token
    //绑定处理类型下拉框
    getDictByCode({ code: 60 }).then((data) => {
      this.handleTypeOptions = data.data.dictValueObj
    })
  },
  methods: {
    onPreview(row, index) {
      if (this.dataObj.picturesUrls) {
        let arr = [
          {
            pic: this.dataObj.picturesUrls + '',
            resultRegion: this.dataObj.picAlarmRegion + '',
          },
        ]
        this.dataObj.aiExtInfoList.forEach((n) => {
          arr.push({
            pic: n.imageInfo.pic,
            resultRegion: JSON.stringify(n),
          })
        })
        this.originList = arr
      } else {
        this.originList = [
          {
            pic: this.picUrl + '',
            resultRegion: '',
          },
        ]
      }
      this.$nextTick(() => {
        this.$refs.ImageViewer.switchPic(0)
      })
    },
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
      })
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.fileList = fileList
    },
    handleRemovePic: function (file, fileList) {
      //删除成功
      this.fileList = fileList
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
    },
    onVideoUploadSuccess(res, file, list) {
      this.videoList = list
    },
    onRemoveVideo(file, fileList) {
      this.videoList = fileList
    },
    beforeUploadVideo(file) {
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
    },
    handleSelectChange(val) {
      let selectedText = ''
      $.each(this.handleTypeOptions, (index, obj) => {
        if (obj.dictKey == val) {
          selectedText = obj.dictValue
          return false
        }
      })
      this.handleForm.remark = selectedText
    },
    submitHandle(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = this.handleForm
          parames.picUrls = util.ilinkArrHandle
            .getqiniuPicUrlArr(this.fileList)
            .toString()
          parames.audioUrls = util.ilinkArrHandle
            .getqiniuPicUrlArr(this.videoList)
            .toString()
          this.requestSubmit(parames)
        }
      })
    },
    requestSubmit(parames) {
      this.loading = true
      alarmHandle(parames).then((res) => {
        if (res.status === 200) {
          this.$message({
            message: '保存成功！',
            type: 'success',
          })
          this.closeFun(true)
        } else {
          this.$message({
            message: res.info,
            type: 'warning',
          })
        }
        this.loading = false
      })
    },
  },
}
</script>

<style lang="scss">
.form-deal-firealarm {
  .el-radio {
    line-height: 28px;
  }
  .tag-handle-type {
    margin: 10px 8px 0 0;
    cursor: pointer;
  }
  .row-img {
    display: flex;
    align-items: center;
    padding: 0 0 10px 20px;
    .desc {
      margin-left: 20px;
      flex: 1;
    }
  }
}
</style>
